package com.ruoyi.airsystem.controller;

import java.util.Collections;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.airsystem.domain.AirDevices;
import com.ruoyi.airsystem.domain.AirRooms;
import com.ruoyi.airsystem.domain.AirFamilies;
import com.ruoyi.airsystem.service.IAirDevicesService;
import com.ruoyi.airsystem.service.IAirRoomsService;
import com.ruoyi.airsystem.service.IAirFamiliesService;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 设备管理Controller
 */
@RestController
@RequestMapping("/airsystem/devices")
public class AirDevicesController extends BaseController {

    @Autowired
    private IAirDevicesService airDevicesService;

    @Autowired
    private IAirRoomsService airRoomsService;

    @Autowired
    private IAirFamiliesService airFamiliesService;

    /**
     * 查询设备管理列表
     */
    @PreAuthorize("@ss.hasPermi('airsystem:devices:list')")
    @GetMapping("/list")
    public TableDataInfo list(AirDevices airDevices) {
        Long userId = SecurityUtils.getUserId();

        if (userId != 1L) {
            // 获取用户关联的家庭
            AirFamilies familyQuery = new AirFamilies();
            familyQuery.setUserId(userId);
            List<AirFamilies> families = airFamiliesService.selectAirFamiliesList(familyQuery);

            if (families.isEmpty()) {
                return getDataTable(Collections.emptyList());
            }

            // 获取家庭下的所有房间
            AirRooms roomQuery = new AirRooms();
            roomQuery.setFamilyId(families.get(0).getFamilyId());
            List<AirRooms> rooms = airRoomsService.selectAirRoomsList(roomQuery);

            if (rooms.isEmpty()) {
                return getDataTable(Collections.emptyList());
            }

            // 设置设备查询的房间ID条件（多个房间ID）
            airDevices.setRoomIds(rooms.stream()
                    .map(AirRooms::getRoomId)
                    .toArray(Long[]::new));
        }

        startPage();
        List<AirDevices> list = airDevicesService.selectAirDevicesList(airDevices);
        return getDataTable(list);
    }

    /**
     * 导出设备管理列表
     */
    @PreAuthorize("@ss.hasPermi('airsystem:devices:export')")
    @Log(title = "设备管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AirDevices airDevices) {
        Long userId = SecurityUtils.getUserId();

        if (userId != 1L) {
            // 获取用户关联的家庭
            AirFamilies familyQuery = new AirFamilies();
            familyQuery.setUserId(userId);
            List<AirFamilies> families = airFamiliesService.selectAirFamiliesList(familyQuery);

            if (families.isEmpty()) {
                ExcelUtil<AirDevices> util = new ExcelUtil<>(AirDevices.class);
                util.exportExcel(response, Collections.emptyList(), "设备管理数据");
                return;
            }

            // 获取家庭下的所有房间
            AirRooms roomQuery = new AirRooms();
            roomQuery.setFamilyId(families.get(0).getFamilyId());
            List<AirRooms> rooms = airRoomsService.selectAirRoomsList(roomQuery);

            if (rooms.isEmpty()) {
                ExcelUtil<AirDevices> util = new ExcelUtil<>(AirDevices.class);
                util.exportExcel(response, Collections.emptyList(), "设备管理数据");
                return;
            }

            // 设置设备查询的房间ID条件（多个房间ID）
            airDevices.setRoomIds(rooms.stream()
                    .map(AirRooms::getRoomId)
                    .toArray(Long[]::new));
        }

        List<AirDevices> list = airDevicesService.selectAirDevicesList(airDevices);
        ExcelUtil<AirDevices> util = new ExcelUtil<>(AirDevices.class);
        util.exportExcel(response, list, "设备管理数据");
    }

    /**
     * 获取设备详细信息
     */
    @PreAuthorize("@ss.hasPermi('airsystem:devices:query')")
    @GetMapping("/{deviceId}")
    public AjaxResult getInfo(@PathVariable Long deviceId) {
        AirDevices airDevice = airDevicesService.selectAirDevicesByDeviceId(deviceId);
        Long userId = SecurityUtils.getUserId();
        if (userId != 1L) {
            if (airDevice == null) {
                return AjaxResult.error("设备不存在");
            }
            // 验证设备所属房间是否属于用户关联的家庭
            AirRooms room = airRoomsService.selectAirRoomsByRoomId(airDevice.getRoomId());
            if (room == null) {
                return AjaxResult.error("设备所属房间不存在");
            }
            AirFamilies familyQuery = new AirFamilies();
            familyQuery.setFamilyId(room.getFamilyId());
            familyQuery.setUserId(userId);
            List<AirFamilies> families = airFamiliesService.selectAirFamiliesList(familyQuery);

            if (families.isEmpty()) {
                return AjaxResult.error("没有权限查看此设备");
            }
        }
        return success(airDevice);
    }

    /**
     * 新增设备
     */
    @PreAuthorize("@ss.hasPermi('airsystem:devices:add')")
    @Log(title = "设备管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AirDevices airDevices) {
        Long userId = SecurityUtils.getUserId();

        if (userId != 1L) {
            // 验证房间是否属于用户关联的家庭
            AirRooms room = airRoomsService.selectAirRoomsByRoomId(airDevices.getRoomId());
            if (room == null) {
                return AjaxResult.error("指定的房间不存在");
            }

            AirFamilies familyQuery = new AirFamilies();
            familyQuery.setFamilyId(room.getFamilyId());
            familyQuery.setUserId(userId);
            List<AirFamilies> families = airFamiliesService.selectAirFamiliesList(familyQuery);

            if (families.isEmpty()) {
                return AjaxResult.error("没有权限在此房间添加设备");
            }
        }

        return toAjax(airDevicesService.insertAirDevices(airDevices));
    }

    /**
     * 修改设备
     */
    @PreAuthorize("@ss.hasPermi('airsystem:devices:edit')")
    @Log(title = "设备管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AirDevices airDevices) {
        Long userId = SecurityUtils.getUserId();

        if (userId != 1L) {
            AirDevices existing = airDevicesService.selectAirDevicesByDeviceId(airDevices.getDeviceId());
            if (existing == null) {
                return AjaxResult.error("设备不存在");
            }

            // 验证原设备所属房间是否属于用户关联的家庭
            AirRooms existingRoom = airRoomsService.selectAirRoomsByRoomId(existing.getRoomId());
            if (existingRoom == null) {
                return AjaxResult.error("设备所属房间不存在");
            }

            AirFamilies familyQuery = new AirFamilies();
            familyQuery.setFamilyId(existingRoom.getFamilyId());
            familyQuery.setUserId(userId);
            List<AirFamilies> families = airFamiliesService.selectAirFamiliesList(familyQuery);

            if (families.isEmpty()) {
                return AjaxResult.error("没有权限修改此设备");
            }

            // 如果修改了房间ID，需要验证新房间是否属于用户关联的家庭
            if (airDevices.getRoomId() != null && !airDevices.getRoomId().equals(existing.getRoomId())) {
                AirRooms newRoom = airRoomsService.selectAirRoomsByRoomId(airDevices.getRoomId());
                if (newRoom == null) {
                    return AjaxResult.error("新指定的房间不存在");
                }

                familyQuery.setFamilyId(newRoom.getFamilyId());
                List<AirFamilies> newFamilies = airFamiliesService.selectAirFamiliesList(familyQuery);

                if (newFamilies.isEmpty()) {
                    return AjaxResult.error("没有权限将设备移动到此房间");
                }
            }

            // 确保房间ID不被修改（如果未提供新房间ID）
            if (airDevices.getRoomId() == null) {
                airDevices.setRoomId(existing.getRoomId());
            }
        }

        return toAjax(airDevicesService.updateAirDevices(airDevices));
    }

    /**
     * 删除设备
     */
    @PreAuthorize("@ss.hasPermi('airsystem:devices:remove')")
    @Log(title = "设备管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deviceIds}")
    public AjaxResult remove(@PathVariable Long[] deviceIds) {
        Long userId = SecurityUtils.getUserId();

        if (userId != 1L) {
            for (Long deviceId : deviceIds) {
                AirDevices existing = airDevicesService.selectAirDevicesByDeviceId(deviceId);
                if (existing == null) {
                    return AjaxResult.error("设备ID为 " + deviceId + " 的记录不存在");
                }
                // 验证设备所属房间是否属于用户关联的家庭
                AirRooms room = airRoomsService.selectAirRoomsByRoomId(existing.getRoomId());
                if (room == null) {
                    return AjaxResult.error("设备所属房间不存在");
                }
                AirFamilies familyQuery = new AirFamilies();
                familyQuery.setFamilyId(room.getFamilyId());
                familyQuery.setUserId(userId);
                List<AirFamilies> families = airFamiliesService.selectAirFamiliesList(familyQuery);

                if (families.isEmpty()) {
                    return AjaxResult.error("没有权限删除设备ID为 " + deviceId + " 的记录");
                }
            }
        }

        return toAjax(airDevicesService.deleteAirDevicesByDeviceIds(deviceIds));
    }
}
